<?php

   /**
    * 
    * @author huxiaomin    2012-1-17  
    * 
    */
    session_start();
    $path = realpath(dirname(__FILE__).'/../');
    define('PATH', $path);
    ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.PATH);
    //require_once('database_config.inc.php');
    //require_once 'sql/DAO.cls.php';
    
    define('MYUNIT_SAVE_DIR',$path.'/testcode/');//单元测试保存位置
    define('MYUNIT_SAVE_DIR_TEMP','temp.php');//脚本临时保存位置
    define('MYUNIT_SAVE_DIR_ERROR',MYUNIT_SAVE_DIR.'error.php');//脚本临时保存位置
    
    set_error_handler("my_customError"); 
    function my_customError()
    {
    	$ob = print_r(func_get_args(),1);
        $s = debug_backtrace();
        $ob .= print_r(array($s[1],$s[2]),1);
        
        file_put_contents(MYUNIT_SAVE_DIR_ERROR,$ob,FILE_APPEND);
        return true;
    }
    
    class TestCodeTest
    {
        //执行
        function ex($body)
        {
            file_put_contents(MYUNIT_SAVE_DIR_ERROR,'');
            $str = "<?php \n";
            $str .= $body;
            file_put_contents(MYUNIT_SAVE_DIR.MYUNIT_SAVE_DIR_TEMP,$str);
            ob_start();
            include MYUNIT_SAVE_DIR.MYUNIT_SAVE_DIR_TEMP;
            $out = ob_get_clean();
            return $out;
        }
        
        //保存
        function saveTime($m)
        {
            @mkdir($m,0777,true);
            $name = date('his').'_test.php';
            return $this->c(MYUNIT_SAVE_DIR.MYUNIT_SAVE_DIR_TEMP,$m.$name);
        }
        
        
        //读取文件
        function readDir($m,$dir_name='')
        {
            $handler = opendir($m);
            $out = '';
            $id = 0;
            $file_array = array();
            while (false !== ($file = readdir($handler))) {
                if($file == '.' || $file == '..')continue;
                $file_array[] = $file; 
            }
            closedir($handler);
            foreach ((array)$file_array as $file)
            {
                $name = file_get_contents($m.$file,false,NULL,5,100);
                $name = mb_substr($name,0,20,'utf-8');
                $name = htmlspecialchars($name, ENT_QUOTES);
                $out .= "<a href='#'  class='file_{$id}' onclick=\"read('{$file}')\">{{$file}}{$name}</a>
                 <img class='file_{$id}' src='cross.gif' onclick=\"del('{$file}','file_{$id}')\" />
                <br />";
                $id ++;
            }
            $out .= "<input type='hidden' id='dir_name' value='{$dir_name}'/>";
            return $out;
        }
        
        //保存至文件夹
        function save($m,$dir_name,$file_name)
        {
            $dir_name = $this->dirName($dir_name);
            @mkdir($m.$dir_name,0777,true);
            return $this->c(MYUNIT_SAVE_DIR.MYUNIT_SAVE_DIR_TEMP,$m.$dir_name.'/'.$file_name);
        }
        
        
        //过滤文件名
        function dirName($dir_name)
        {
            $str = array('.'=>'','\\'=>'','/'=>'',);
            return strtr($dir_name,$str);
        }
        
        //保存文件
        function c($from,$to)
        {
            if (file_exists($to))
            {
                $to .= '.php';
            }
            @copy($from,$to);
            $pos = strrpos($to,'/');
            return substr($to,$pos);
        }
        
        
        //删除文件
        function del($file,$dir='')
        {
            $dir =  $this->dirName($dir);
            if ($dir)
            {
                $m = MYUNIT_SAVE_DIR.'code/'.$dir.'/';
            }else {
                $m = MYUNIT_SAVE_DIR.'code/'.date('y-m-d').'/';
            }
            @unlink($m.$file);
        }
        
    }
    
    //////////////////////////////////////////////权限检查，以及日志
   /* $dao = new DAO();
    if (!isset($_SESSION['fe7afd244f2c4745a0316adc7d94cc1e']))
    {
        $user = mysql_real_escape_string(trim ($_REQUEST['user']));
        $password = trim ($_REQUEST['pwd']);
        $password = md5($password);
        $sql = "select id From salers where username='{$user}' and password = '{$password}'";
        if (!$dao->GetValue($sql))
        {
            echo "用户密码错误";exit;
        }
        $_SESSION['fe7afd244f2c4745a0316adc7d94cc1e'] = array($user,$password);
    }
    else {
        $user_info = $_SESSION['fe7afd244f2c4745a0316adc7d94cc1e'];
        $sql = "select id From salers where username='{$user_info[0]}' and password = '{$user_info[1]}'";
        if (!$dao->GetValue($sql))
        {
            echo "用户密码错误";exit;
        }
        
    }*/
    
    
    
    /**
     * 日志    unit_log_1.log.txt  unit_log_2.log.txt unit_log_3.log.txt unit_log_4.log.txt 轮流保存，大约半月一次。
     * @param  $string 脚本内容
     * @param  $crm_id 执行人
     */
    function unit_log($string)
    {
        $user = $_SESSION['fe7afd244f2c4745a0316adc7d94cc1e'][0];
        $log_temp = MYUNIT_SAVE_DIR.'log_temp';
        $context = 1;
        if (file_exists($log_temp))
        {
            $context = file_get_contents($log_temp);
        }
        
        $day   =  date('d') + date('m') % 2 * 32;
        $num = ceil($day / 16);
        $num_2 = $num * 2 - 1 ;
        
        if (empty($context) || !in_array((int)$context , array($num_2,$num_2 + 1 ))  )
        {
            $context = $num_2;
        }
        
        $FILE_TYPE = FILE_APPEND;
        if ($num_2 == $context)
        {
            $FILE_TYPE = FILE_BINARY;
            $context ++;
            file_put_contents($log_temp,$context);
        }
        
        $file_name = MYUNIT_SAVE_DIR."unit_log_{$num}.log.txt";
        $time = date('Y-m-d H:i:s');
        $string = "\n//**unit_log={$user}&time={$time}\n{$string}";
        file_put_contents($file_name,$string,$FILE_TYPE);
        
    }
    //////////////////////////////////////////code的操作。
    $flag = '';
    if (isset($_REQUEST['flag'])){
        $flag = $_REQUEST['flag'];
    }
    $TestCodeTest = new TestCodeTest();
    
    if ($flag == 'ex0')//单独执行
    {
        $body = trim($_REQUEST['data']);
        unit_log($body);
        $out = $TestCodeTest->ex($body);
        $return = array('data'=>$out);
        echo json_encode($return);
        exit;
    }
    else if ($flag == 'ex1')//执行并保存
    {
        $body = trim($_REQUEST['data']);
        unit_log($body);
        $out = $TestCodeTest->ex($body);
        $m = MYUNIT_SAVE_DIR.'code/'.date('y-m-d').'/';
        $TestCodeTest->saveTime($m);
        $return = array('data'=>$out);
        echo json_encode($return);
        exit;
    }
    else if ($flag == 'read_dir')//取文件下所有文件
    {
        $dir_name = trim($_REQUEST['dir_name']);
        if ($dir_name ==  '') $dir_name = date('y-m-d');
        $m = MYUNIT_SAVE_DIR.'code/'.$dir_name.'/';
        $out = $TestCodeTest->readDir($m,$dir_name);
        $return = array('data'=>$out);
        echo json_encode($return);
        exit;
    }elseif ($flag == 'read')//读文件内容
    {
        $file = trim($_REQUEST['file']);
        $dir_name = trim($_REQUEST['dir_name']);
        if ($dir_name ==  '') $dir_name = date('y-m-d');
        $m = MYUNIT_SAVE_DIR.'code/'.$dir_name.'/';
        $out = file_get_contents($m.$file);
        $out = substr($out,7);
        $return = array('data'=>$out);
        echo json_encode($return);
        exit;
        
    }elseif ($flag == 'del')//删除文件
    {
        $file = trim($_REQUEST['file']);
        $dir_name = trim($_REQUEST['dir_name']);
        if ($dir_name ==  '') $dir_name = date('y-m-d');
        $m = MYUNIT_SAVE_DIR.'code/'.$dir_name.'/';
        @unlink($m.$file);
        $return = array('data'=>'');
        echo json_encode($return);
        exit;
        
    }elseif ($flag == 'save')//保存到指定文件夹
    {
        $body = trim($_REQUEST['data']);
        $dir  = trim($_REQUEST['dir']);
        if ($dir == ''){
            echo '请正确填写文件夹路径';exit;
        }
        //$out = $TestCodeTest->ex($body);
        $m = MYUNIT_SAVE_DIR.'code/';
        $file_name = date('his').'_test.php';
        $TestCodeTest->save($m,$dir,$file_name);
        $return = array('data'=>'');
        echo json_encode($return);
        exit;
    }
    elseif ($flag == 'getError')//获取错误信息
    {
        $content = file_get_contents(MYUNIT_SAVE_DIR_ERROR);
        $return = array('data'=>$content);
        echo json_encode($return);
        exit;
    }
    
    
    //js的单独页面显示
    if ($flag == 'jsEx'){
        $str = trim($_REQUEST['data']);
        file_put_contents(MYUNIT_SAVE_DIR.MYUNIT_SAVE_DIR_TEMP,$str);
        echo json_encode(array(1));
        exit;
    }
    else if ($flag == 'jsExShow'){
        echo <<< HEAD
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="/res/js/lib/jquery.js"></script>
<title>js单元测试</title>

</head>
<body>
HEAD;
        echo file_get_contents(MYUNIT_SAVE_DIR.MYUNIT_SAVE_DIR_TEMP);
        
        echo <<< HEAD2
        </body>
        </html>
HEAD2;
         
        exit;
    }
    
    if ($flag != 'fe7afd244f2c4745a0316adc7d94cc1e')
    {
        //exit;
    }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="/res/lib/thickbox/common.css" rel="stylesheet" type="text/css" />
<link href="/res/lib/thickbox/thickbox.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/res/js/lib/jquery.js"></script>
<script type="text/javascript" src="/res/lib/thickbox/thickbox-compressed.js"></script>


<title>单元测试</title>
<style>
th{color:#000099;front-size:70%;fontt-weight:normal;background:#D3DCE3;}
td{background:#D3DCE3;}
</style>
</head>
<body>
<div id="show_div" style="display:none;">
<textarea cols="125" rows="23" id="show_div_content"></textarea>
</div>

<form method="post">
        <table>
            <thead>
            <tr>
                    <th>文件列表：</th>
                    <th>
                        <!--  
                        <input type="button" onclick="ex(1);" value="执行下面代码并保存"/>
                        <input type="button" onclick="read_dir(0);" value="显示所有文件"/><br />
                        -->
                        保存路径：<input type='text' id='file_name' value=''/>
                        <input type="button" onclick="save();" value="保存"/>
                        <input type="button" onclick="read_dir(1);" value="打开"/><br />
                        
                    </th>
                    <th>
                            运行结果：<input type="button" onclick="ex(0);" value="执行php"/>
                            <input type="button"  
            id="common_thickbox_input"
            onclick="$('#show_div_content').val($('#error').val())"
             class="thickbox" 
            value="查看错误信息" 
             alt="#TB_inline?height=350&width=800&inlineId=show_div"'
            title="专用弹窗"/>
                        <input type="hidden" id="jsEx" value="执行js" class="thickbox"     title="执行html，js" style="margin-left:10px"
            alt="/test.code.php?flag=jsExShow&KeepThis=true&TB_iframe=true&height=250&width=800" />
                        <input type="hidden" onclick="jsExcute();" value="执行html，js"/>
                        
                            
                    </th>
            
            </tr>
                
            </thead>
            <tbody>
                <tr>
                     <td rowspan="2">
                        <div id="files_list"></div>
                     </td>
                    
                     <td>
                     <div >
                            <textarea cols="100" rows="35" id="code">
                            </textarea>
                     </div>
                     </td>
                    <td>
                     <div >
                            <textarea cols="50" rows="35" id="files">
                            </textarea>
                     </div> 
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                         <textarea cols="156" rows="8" id="error">
                         </textarea>
                    </td>
                </tr>
                
            </tbody>
        </table>
</form>
<script>
    //单独页面执行
    function jsExcute()
    {
        var data_ =encodeURIComponent($("#code").val()) ;
        $.ajax({
            url:'/test.code.php',
            type:'post',
            data:'flag=jsEx&data='+data_+'&cache='+Math.random(),
            dataType:'json',
            success:function(json){
                try{
                        $("#jsEx").trigger("click");
                    }catch(e){}
            },
            error:function(json){
                    alert(json.responseText);
                }
            });
        
    }

    // 0:执行，1：默认保存
    function ex(v)
    {
        
        var data_ =encodeURIComponent($("#code").val()) ;
        $.ajax({
            url:'/test.code.php',
            type:'post',
            data:'flag=ex'+v+'&data='+data_+'&cache='+Math.random(),
            dataType:'json',
            async:false,
            success:function(json){
                try{
                        $("#files").val(json.data);
                    }catch(e){}
            },
            error:function(json){
                    alert(json.responseText);
                }
            });
        error();
    }
    //0:打开默认文件夹， 1：打开指定文件夹
    function read_dir(v)
    {
        var dir_name = encodeURIComponent($("#file_name").val()) ;
        if(v == 0)dir_name = '';
        $.ajax({
        	url:'/test.code.php',
            type:'post',
            data:'flag=read_dir&dir_name='+dir_name+'&cache='+Math.random(),
            dataType:'json',
            success:function(json){
                try{
                        $("#files_list").html(json.data);
                    }catch(e){}
            },
            error:function(json){
                    alert(json.responseText);
                }
            });
    }

    
    //保存至指定文件夹
    function save()
    {
        var data_ =encodeURIComponent($("#code").val()) ;
        var dir =encodeURIComponent($("#file_name").val()) ;
        $.ajax({
        	url:'/test.code.php',
            type:'post',
            data:'flag=save&data='+data_+'&dir='+dir+'&cache='+Math.random(),
            dataType:'json',
            success:function(json){
                try{
                        //$("#files").val(json.data);
                        alert("保存成功");
                    }catch(e){}
            },
            error:function(json){
                    alert(json.responseText);
                }
            });
    }
    
    //点击文件链接，获取文件
    function read(file)
    {
        var dir_name = encodeURIComponent($("#dir_name").val());
        $.ajax({
        	url:'/test.code.php',
            type:'post',
            data:'flag=read&file='+file+'&dir_name='+dir_name+'&cache='+Math.random(),
            dataType:'json',
            success:function(json){
                try{
                        $("#code").val(json.data);
                    }catch(e){}
            },
            error:function(json){
                    alert(json.responseText);
                }
            });
    }
    //点击文件链接图片，删除文件
    function del(file,cl)
    {
        var dir_name = encodeURIComponent($("#dir_name").val());
        $.ajax({
        	url:'/test.code.php',
            type:'post',
            data:'flag=del&file='+file+'&dir_name='+dir_name+'&cache='+Math.random(),
            dataType:'json',
            success:function(json){
                try{
                        $("."+cl).remove();
                    }catch(e){}
            },
            error:function(json){
                    alert(json.responseText);
                }
            });
    }

    //获取错误信息
    function error(){
    	$.ajax({
            url:'/test.code.php',
            type:'post',
            data:'flag=getError&cache='+Math.random(),
            dataType:'json',
            success:function(json){
                try{
                       $("#error").val(json.data);
                    }catch(e){}
            },
            error:function(json){
                    alert(json.responseText);
                }
            });
    }

</script>
</body>
</html>

    
        
    